import { request } from './api'
import type {
  ApiResponse,
  PageResult,
  WideTable,
  WideTableField,
  WideTableDataVO
} from '@/types'

// 查询参数接口
export interface WideTableQueryParams {
  current: number
  size: number
  name?: string
  displayName?: string
  type?: 'ONLINE' | 'OFFLINE'
  status?: 'ACTIVE' | 'INACTIVE'
  creator?: string
  createTimeStart?: string
  createTimeEnd?: string
  sortField?: string
  sortOrder?: 'asc' | 'desc'
}

// 创建数据宽表参数
export interface CreateWideTableParams {
  name: string
  displayName: string
  description?: string
  type: 'ONLINE' | 'OFFLINE'
  dataSource?: string
  esIndexName?: string
  tableConfig?: any
  fields: WideTableFieldParams[]
}

// 字段参数接口
export interface WideTableFieldParams {
  fieldName: string
  displayName: string
  fieldType: 'STRING' | 'NUMBER' | 'DATE' | 'BOOLEAN'
  fieldLength?: number
  precisionScale?: string
  nullable?: boolean
  defaultValue?: string
  description?: string
  isDisplayField?: boolean
  isQueryField?: boolean
  sortOrder?: number
}

// 数据查询参数
export interface WideTableDataQueryParams {
  wideTableId: number
  current: number
  size: number
  selectFields?: string[]
  conditions?: QueryCondition[]
  aggregation?: AggregationConfig
  sortField?: string
  sortOrder?: 'asc' | 'desc'
}

// 查询条件
export interface QueryCondition {
  field: string
  operator: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'nin' | 'like' | 'exists' | 'range'
  value?: any
  startValue?: any
  endValue?: any
  logic?: 'and' | 'or'
}

// 聚合配置
export interface AggregationConfig {
  groupByFields?: string[]
  functions?: AggregationFunction[]
  havingConditions?: QueryCondition[]
}

// 聚合函数
export interface AggregationFunction {
  function: 'count' | 'sum' | 'avg' | 'min' | 'max' | 'distinct_count'
  field: string
  alias?: string
}

/**
 * 数据宽表服务
 */
export const wideTableService = {
  /**
   * 分页查询数据宽表
   */
  getWideTablePage: (params: WideTableQueryParams): Promise<ApiResponse<PageResult<WideTable>>> => {
    return request.get('/wide-tables', params)
  },

  /**
   * 根据ID查询数据宽表详情
   */
  getWideTableById: (id: number): Promise<ApiResponse<WideTable>> => {
    return request.get(`/wide-tables/${id}`)
  },

  /**
   * 查询用户可访问的数据宽表列表
   */
  getAccessibleWideTableList: (): Promise<ApiResponse<WideTable[]>> => {
    return request.get('/wide-tables/accessible')
  },

  /**
   * 创建数据宽表
   */
  createWideTable: (params: CreateWideTableParams): Promise<ApiResponse<number>> => {
    return request.post('/wide-tables', params)
  },

  /**
   * 更新数据宽表
   */
  updateWideTable: (id: number, params: CreateWideTableParams): Promise<ApiResponse<boolean>> => {
    return request.put(`/wide-tables/${id}`, params)
  },

  /**
   * 删除数据宽表
   */
  deleteWideTable: (id: number): Promise<ApiResponse<boolean>> => {
    return request.delete(`/wide-tables/${id}`)
  },

  /**
   * 根据宽表ID查询字段列表
   */
  getWideTableFields: (wideTableId: number): Promise<ApiResponse<WideTableField[]>> => {
    return request.get(`/wide-tables/${wideTableId}/fields`)
  },

  /**
   * 更新宽表字段配置
   */
  updateWideTableFields: (wideTableId: number, fields: WideTableFieldParams[]): Promise<ApiResponse<boolean>> => {
    return request.put(`/wide-tables/${wideTableId}/fields`, fields)
  },

  /**
   * 初始化在线数据宽表索引
   */
  initOnlineWideTableIndex: (wideTableId: number): Promise<ApiResponse<boolean>> => {
    return request.post(`/wide-tables/${wideTableId}/index`)
  },

  /**
   * 查询宽表数据
   */
  queryWideTableData: (params: WideTableDataQueryParams): Promise<ApiResponse<WideTableDataVO>> => {
    return request.post('/wide-tables/data/query', params)
  },

  /**
   * 聚合查询宽表数据
   */
  aggregateWideTableData: (params: WideTableDataQueryParams): Promise<ApiResponse<Record<string, any>>> => {
    return request.post('/wide-tables/data/aggregate', params)
  },

  /**
   * 导出宽表数据
   */
  exportWideTableData: (params: WideTableDataQueryParams): Promise<ApiResponse<string>> => {
    return request.post('/wide-tables/data/export', params)
  },

  /**
   * 获取宽表字段统计信息
   */
  getFieldStats: (wideTableId: number, fieldName: string): Promise<ApiResponse<any>> => {
    return request.get(`/wide-tables/${wideTableId}/fields/${fieldName}/stats`)
  },

  /**
   * 检查宽表名称是否可用
   */
  checkWideTableName: (name: string, excludeId?: number): Promise<ApiResponse<boolean>> => {
    const params: any = { name }
    if (excludeId) {
      params.excludeId = excludeId
    }
    return request.get('/wide-tables/check-name', params)
  },

  /**
   * 激活/停用数据宽表
   */
  updateWideTableStatus: (id: number, status: 'ACTIVE' | 'INACTIVE'): Promise<ApiResponse<boolean>> => {
    return request.put(`/wide-tables/${id}/status?status=${status}`)
  },

  /**
   * 同步宽表结构到Elasticsearch
   */
  syncWideTableToEs: (id: number): Promise<ApiResponse<boolean>> => {
    return request.post(`/wide-tables/${id}/sync`)
  },

  /**
   * 获取宽表数据总数
   */
  getWideTableDataCount: (id: number): Promise<ApiResponse<number>> => {
    return request.get(`/wide-tables/${id}/data/count`)
  },

  /**
   * 清空宽表数据
   */
  clearWideTableData: (id: number): Promise<ApiResponse<boolean>> => {
    return request.delete(`/wide-tables/${id}/data`)
  },

  /**
   * 获取统计信息
   */
  getStatistics: (): Promise<ApiResponse<{
    total: number
    online: number
    offline: number
    active: number
  }>> => {
    return request.get('/wide-tables/statistics')
  }
}

export default wideTableService